package com.atguigu.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/12/5 09:17
 */
public class Dwd_01_DwdTrafficLog extends BaseAppV1 {
    
    private final String START = "start";
    private final String ACTION = "action";
    private final String DISPLAY = "display";
    private final String ERR = "err";
    private final String PAGE = "page";
    
    public static void main(String[] args) {
        new Dwd_01_DwdTrafficLog().init(
            3001,
            2,
            "Dwd_01_DwdTrafficLog",
            Constant.TOPIC_ODS_LOG
        );
        
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        
        //任务:
        //1. 读取 topic 数据, 做数据清洗
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        
        // 2. 做新老客户纠正
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        // 3. 分流: 5 个流
        //测输出流
        Map<String, DataStream<JSONObject>> streams = splitStream(validatedStream);
        // 4. 5 个流分别写入到不同的 topic 中
        writeToKafka(streams);
    }
    
    private void writeToKafka(Map<String, DataStream<JSONObject>> streams) {
        streams.get(PAGE).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(ERR).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(DISPLAY).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ACTION).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
    }
    
    private Map<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
//        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display", TypeInformation.of(JSONObject.class));
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display"){};
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action"){};
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err"){};
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page"){};
        // 分出 5 个流, 5 个流分别存储 5 种日志
        // start  action display page err
        // start => 主流
        // 其他 => 测输出流
        SingleOutputStreamOperator<JSONObject> startStream = validatedStream
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
    
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject start = obj.getJSONObject("start");
                    if (start != null) {
                        // 启动日志
                        out.collect(obj);
                    }else{
                        // 曝光
                        JSONArray displays = obj.getJSONArray("displays");
                        if (displays != null) {
                            for (int i = 0; i < displays.size(); i++) {
                                JSONObject display = displays.getJSONObject(i);
                                display.putAll(common); // 把通用的一些字段放入到 display 中
                                display.put("ts", obj.getLong("ts"));
                                ctx.output(displayTag, display);
                            }
                            // 把曝光表数据从 obj 中删除, 为了不影响后面(page, err)
                            obj.remove("displays");
                        }
                        // 活动
                        JSONArray actions = obj.getJSONArray("actions");
                        if (actions != null) {
                            for (int i = 0; i < actions.size(); i++) {
                                JSONObject action = actions.getJSONObject(i);
                                action.putAll(common); // 把通用的一些字段放入到 display 中
                                ctx.output(actionTag, action);
                            }
                            // 把曝光表数据从 obj 中删除, 为了不影响后面(page, err)
                            obj.remove("actions");
                        }
                        
                        //err
                        JSONObject err = obj.getJSONObject("err");
                        if (err != null) {
                            ctx.output(errTag, obj);
                            obj.remove("err");
                        }
    
                        //page
                        JSONObject page = obj.getJSONObject("page");
                        if (page != null) {
                            ctx.output(pageTag, obj);
                        }
    
                    }
    
                }
            });
        
        // 返回 5 个流: List  Tuple5   Map<String, Stream>
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        DataStream<JSONObject> errStream = startStream.getSideOutput(errTag);
        DataStream<JSONObject> actionStream = startStream.getSideOutput(actionTag);
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
    
        Map<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, startStream);
        streams.put(ACTION, actionStream);
        streams.put(DISPLAY, displayStream);
        streams.put(ERR, errStream);
        streams.put(PAGE, pageStream);
        
        return streams;
    
    
    }
    
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .map(new RichMapFunction<JSONObject, JSONObject>() {
                
                private ValueState<String> firstVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDate", String.class));
                }
                
                @Override
                public JSONObject map(JSONObject obj) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.tsToDate(ts);
                    String isNew = common.getString("is_new");
    
                    String firstVisitDate = firstVisitDateState.value();
    
                    if ("1".equals(isNew)) {
                        // 首日首次
                        if (firstVisitDate == null) {
                            // 不用纠正
                            //把今天存入到状态中
                            firstVisitDateState.update(today);
                        }else{
                            if (!today.equals(firstVisitDate)) {
                                // 今天不是首日, 纠正 is_new 1=>1
                                common.put("is_new", "0");
                            }
                        }
                    }else {
                        // 当程序启动之后, 如果用户是老用户,则状态也是 null, 这个时候应该把状态设置为昨天...
                        if(firstVisitDate == null){
                            String yesterday = AtguiguUtil.tsToDate(ts - 24 * 60 * 60 * 1000);
                            firstVisitDateState.update(yesterday);
                        }
                    }
                    
                    return obj;
                    // 今天 5 号是 0, 则首次一定不是 5 号
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
            .filter(json -> {
                try {
                    JSON.parseObject(json);
                    return true;
                } catch (Exception e) {
                    System.out.println("json格式数据不对: " + json);
                    return false;
                }
            })
            .map(JSON::parseObject);
    }
}
/*
新老客户为啥纠正:
    is_new字段是如何产生?
    
    如果 is_new 出错, 只会把老用户识别为新用户
    
    如何纠正?
        keyBy: mid
        is_new=1
            搞一个状态: 存储这个用户的首次访问日期
            首次: state=null
                不用纠正
                把今天存储到状态中
            state != null
                today==fistDate
                    不用纠正
                today != fistDate
                    需要纠正: 1=>0
    
    
 */